package sy.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import sy.pageModel.DataGrid;
import sy.pageModel.OrderDoctor;
import sy.pageModel.OrderHealth;
import sy.service.OrderHealthServiceI;
import sy.util.DateTimeUtility;
import sy.util.DateUtil;
import sy.util.StringUtil;

@Service("orderHealthService")
public class OrderHealthServiceImpl extends BaseService implements OrderHealthServiceI {
	
	@Override
	public DataGrid datagrid(OrderHealth order) throws Exception {
		DataGrid dg = new DataGrid();
		String sql = "select count(*) from xj_be_doctor where yyj='3'";
		sql = addWhere(order, sql);
		System.out.println(sql);
		long total = template.queryForLong(sql);
		System.out.println(total);
		dg.setTotal(total);
		
		sql = "select id, did, vnumber, name, state, phone, date_time, sex, id_card, birthday, dept_id, departmetn_id, brief, sq_time, is_urgent, ys_money, sj_money, comments, is_independence "
		      + "from xj_be_doctor where yyj='3'";
		sql = addWhere(order, sql);
		sql = addOrderBy(order, sql);
		sql = addLimit(order, sql);
		System.out.println(sql);
		final List<OrderHealth> orderList = new ArrayList<OrderHealth>();
        template.query(sql, new RowCallbackHandler(){
            public void processRow(ResultSet rs) throws SQLException {
            	OrderHealth order = new OrderHealth();
                order.setId(rs.getString("id"));
                order.setOrderId(rs.getString("did"));
                order.setCardId(rs.getString("vnumber"));
                order.setName(rs.getString("name"));
                order.setStatus(rs.getString("state"));
                order.setMobile(rs.getString("phone"));
                order.setCreateTime(rs.getString("date_time"));
                order.setGender(rs.getString("sex"));
                order.setCid(rs.getString("id_card"));
                order.setBornDate(rs.getString("birthday"));
                order.setHospital(rs.getString("dept_id"));
                order.setDepartment(rs.getString("departmetn_id"));
                order.setRequirement(rs.getString("brief"));
                order.setServiceTime(rs.getString("sq_time"));
                order.setIsUrgent(rs.getString("is_urgent"));
                order.setEstimateFee(rs.getDouble("ys_money"));
                order.setActualFee(rs.getDouble("sj_money"));
                order.setServiceDetails(rs.getString("comments"));
                order.setIsIndependence(rs.getString("is_independence"));
            	orderList.add(order);
            }});
		dg.setRows(orderList);		
		return dg;
	}
	
	@Override
	public DataGrid datagridForAccepted(OrderHealth order) throws Exception {
		DataGrid dg = new DataGrid();
		String sql = "select count(*) from xj_be_doctor where yyj='3' and state='" + OrderDoctor.ORDER_STATUS_ID_ACCEPTED + "'";
		sql = addWhere(order, sql);
		System.out.println(sql);
		long total = template.queryForLong(sql);
		System.out.println(total);
		dg.setTotal(total);
		
		sql = "select id, did, vnumber, name, state, phone, date_time, sex, id_card, birthday, dept_id, departmetn_id, brief, sq_time, is_urgent, ys_money, sj_money, comments, is_independence "
		      + "from xj_be_doctor where yyj='3' and state='" + OrderDoctor.ORDER_STATUS_ID_ACCEPTED + "'";
		sql = addWhere(order, sql);
		sql = addOrderBy(order, sql);
		sql = addLimit(order, sql);
		System.out.println(sql);
		final List<OrderHealth> orderList = new ArrayList<OrderHealth>();
        template.query(sql, new RowCallbackHandler(){
            public void processRow(ResultSet rs) throws SQLException {
            	OrderHealth order = new OrderHealth();
                order.setId(rs.getString("id"));
                order.setOrderId(rs.getString("did"));
                order.setCardId(rs.getString("vnumber"));
                order.setName(rs.getString("name"));
                order.setStatus(rs.getString("state"));
                order.setMobile(rs.getString("phone"));
                order.setCreateTime(rs.getString("date_time"));
                order.setGender(rs.getString("sex"));
                order.setCid(rs.getString("id_card"));
                order.setBornDate(rs.getString("birthday"));
                order.setHospital(rs.getString("dept_id"));
                order.setDepartment(rs.getString("departmetn_id"));
                order.setRequirement(rs.getString("brief"));
                order.setServiceTime(rs.getString("sq_time"));
                order.setIsUrgent(rs.getString("is_urgent"));
                order.setEstimateFee(rs.getDouble("ys_money"));
                order.setActualFee(rs.getDouble("sj_money"));
                order.setServiceDetails(rs.getString("comments"));
                order.setIsIndependence(rs.getString("is_independence"));
            	orderList.add(order);
            }});
		dg.setRows(orderList);		
		return dg;
	}
	
	private String addWhere(OrderHealth order, String sql) {
		if(!StringUtil.isNullOrEmpty(order.getOrderId())) {
			sql += " and did like '%" + order.getOrderId() + "%'";
		}
		if(!StringUtil.isNullOrEmpty(order.getCardId())) {
			sql += " and vnumber like '%" + order.getCardId() + "%'";
		}
		if(!StringUtil.isNullOrEmpty(order.getName())) {
			sql += " and name like '%" + order.getName() + "%'";
		}
		if(!StringUtil.isNullOrEmpty(order.getMobile())) {
			sql += " and phone like '%" + order.getMobile() + "%'";
		}
		if(!StringUtil.isNullOrEmpty(order.getCreateTimeStart())) {
			sql += " and date_time >= '" + order.getCreateTimeStart() + "'";
		}
		if(!StringUtil.isNullOrEmpty(order.getCreateTimeEnd())) {
			sql += " and date_time <= '" + order.getCreateTimeEnd() + "'";
		}
		return sql;
	}
	
	private String addLimit(OrderHealth order, String sql) {
		int fromRow = (order.getPage() - 1) * order.getRows();
	    sql += " limit " + fromRow + "," + order.getRows();
	    return sql;
	}
	
	private String addOrderBy(OrderHealth order, String sql) {
		if (order.getSort() != null) {
			if("cardId".equals(order.getSort())) {
				order.setSort("vnumber");
			} else if("name".equals(order.getSort())) {
				order.setSort("convert(name using gbk)");
			} else if("createTime".equals(order.getSort())) {
				order.setSort("date_time");
			} else if("mobile".equals(order.getSort())) {
				order.setSort("phone");
			} else if("orderId".equals(order.getSort())) {
				order.setSort("did");
			} else if("statusName".equals(order.getSort())) {
				order.setSort("state");
			} else if("bornDate".equals(order.getSort())) {
				order.setSort("birthday");
			} else if("genderName".equals(order.getSort())) {
				order.setSort("sex");
			} else if("cid".equals(order.getSort())) {
				order.setSort("id_card");
			} else if("hospital".equals(order.getSort())) {
				order.setSort("dept_id");
			} else if("department".equals(order.getSort())) {
				order.setSort("departmetn_id");
			} else if("serviceTime".equals(order.getSort())) {
				order.setSort("sq_time");
			} else if("isUrgentName".equals(order.getSort())) {
				order.setSort("is_urgent");
			} else if("isIndependenceName".equals(order.getSort())) {
				order.setSort("is_independence");
			}
			sql += " order by " + order.getSort() + " " + order.getOrder();
		}
		return sql;
	}
	
	@Override
	@Transactional
	public OrderHealth add(OrderHealth order) throws Exception {
		System.out.println(order);
		//得到urgent的天数
		int urgentDays = this.getUrgentDays("3");
		String isUrgent = DateTimeUtility.isXWorkingDaysEarlier(order.getServiceTime(), urgentDays) ? "N" : "Y";
	    order.setIsUrgent(isUrgent);
	    Date now = new Date();
	    order.setCreateTime(DateUtil.format(now));
	    order.setId(java.util.UUID.randomUUID().toString());
	    order.setOrderId("Y-" + order.getCardId() + "-" + DateUtil.format(now, "yyyyMMddHHmmss"));
		
		String sql = "insert into xj_be_doctor (id,name,sex,birthday,vnumber,id_card,dept_id,departmetn_id,sq_time,state,date_time,brief,yyj,did,is_urgent,phone,is_independence) " + 
		             "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		
		Object[] paras = new Object[] {
				  order.getId(),
				  order.getName(),
				  order.getGender(),
				  order.getBornDate(),
				  order.getCardId(),
				  order.getCid(),
				  order.getHospital(),
				  order.getDepartment(),
				  order.getServiceTime(),
				  OrderDoctor.ORDER_STATUS_ID_WAIT_ACCEPT,
				  order.getCreateTime(),
				  order.getRequirement(),
				  "3",
				  order.getOrderId(),
				  order.getIsUrgent(),
				  order.getMobile(),
				  order.getIsIndependence()
		};
		
		int affectRow = 0;
		try {
		    affectRow = template.update(sql, paras);
		} catch(Exception e) {
			e.printStackTrace();
			throw new RuntimeException("添加订单失败，请联系系统管理员！");
		}
		if(affectRow == 0) {
			throw new RuntimeException("添加订单失败，请联系系统管理员！");
		}
		
	    System.out.println(order);
	    return order;
	}
	
	@Override
	@Transactional
	public OrderHealth edit(OrderHealth order) throws Exception {
		String sql = "update xj_be_doctor set dept_id=?,departmetn_id=?,brief=?,ys_money=?,sj_money=?,comments=?,state=?,is_independence=?" 
		             + " where id=?";
		System.out.println(sql);
		order.setStatus(orderStatus(order.getStatus()));
		Object[] paras = new Object[] {
		    order.getHospital(),
		    order.getDepartment(),
		    order.getRequirement(),
		    order.getEstimateFee(),
		    order.getActualFee(),
		    order.getServiceDetails(),
		    order.getStatus(),
		    order.getIsIndependence(),
		    order.getId()
		};
		editOrderBySql(sql,paras);
		updateMenber(order.getCardId(),order.getOrderId(),order.getActualFee(),order.getStatus());
		return order;
	}
	
	@Override
	@Transactional
	public OrderHealth addDetails(OrderHealth order) throws Exception {
		String sql = "update xj_be_doctor set ys_money=?,sj_money=?,comments=?,state=?" 
		             + " where id=?";
		System.out.println(sql);
		Object[] paras = new Object[] {
		    order.getEstimateFee(),
		    order.getActualFee(),
		    order.getServiceDetails(),
		    order.getStatus(),
		    order.getId()
		};
		editOrderBySql(sql,paras);
		return order;
	}

	@Override
	public OrderHealth editHealthSave(OrderHealth order) {
		String sql = "update xj_be_doctor set dept_id=?,departmetn_id=?,brief=?,ys_money=?,sj_money=?,comments=?,is_independence=?  where id=?";
		System.out.println(sql);
		order.setStatus(orderStatus(order.getStatus()));
		Object[] paras = new Object[] {
				order.getHospital(),
				order.getDepartment(),
				order.getRequirement(),
				order.getEstimateFee(),
				order.getActualFee(),
				order.getServiceDetails(),
				order.getIsIndependence(),
				order.getId()
		};
		editOrderBySql(sql,paras);
		return order;
	}

	@Override
	public OrderHealth editOrderStatus(OrderHealth order) {
		String sql = "update xj_be_doctor set state=? where id=?";
		order.setStatus(OrderDoctor.ORDER_STATUS_ID_CANCELLED);
		Object[] paras = new Object[] {
				order.getStatus(),
				order.getId()
		};
		editOrderBySql(sql,paras);
		return order;
	}

	private int getUrgentDays(String typeId) {
		String sql = "select c_day from xj_subscribe where typeid=?";
		System.out.println(sql);
		int result = template.queryForInt(sql, new Object[]{typeId});
		System.out.println(result);
		return result;
	}

}
